package com.jcbase.core.task;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RecursiveAction;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jcbase.core.weixin.template.DataItem;
import com.jcbase.model.RisebdCoupon;
import com.jcbase.model.RisebdCouponMember;
import com.jcbase.model.RisebdCouponRule;
import com.jcbase.service.CacheService;
import com.jcbase.service.CompleteService;
import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.tx.Tx;

/**
 * @category 发送优惠券任务,无需返回结果的子任务
 * @author yiz
 *
 */
public class SendCouponTask extends RecursiveAction {

	private static final Logger logger = LoggerFactory.getLogger(SendCouponTask.class);

	/**
	 * 
	 */
	private static final long serialVersionUID = -5292738303233682354L;

	private int start;

	private int end;

	private int threshold;

	private String[] memberIds;

	private RisebdCouponRule couponRule;

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getEnd() {
		return end;
	}

	public void setEnd(int end) {
		this.end = end;
	}

	public int getThreshold() {
		return threshold;
	}

	public void setThreshold(int threshold) {
		this.threshold = threshold;
	}

	public String[] getMemberIds() {
		return memberIds;
	}

	public void setMemberIds(String[] memberIds) {
		this.memberIds = memberIds;
	}

	public RisebdCouponRule getCouponRule() {
		return couponRule;
	}

	public void setCouponRule(RisebdCouponRule couponRule) {
		this.couponRule = couponRule;
	}

	public SendCouponTask(int start, int end, int threshold, String[] memberIds, RisebdCouponRule couponRule) {
		this.start = start;
		this.end = end;
		this.threshold = threshold;
		this.memberIds = memberIds;
		this.couponRule = couponRule;
	}

	@Override
	protected void compute() {
		if (end - start <= threshold) {
			sendProcess(start, end, memberIds, couponRule);
		} else {
			int middle = (end + start) / 2;
			SendCouponTask leftTask = new SendCouponTask(start, middle, threshold, memberIds, couponRule);
			SendCouponTask rightTask = new SendCouponTask(middle + 1, end, threshold, memberIds, couponRule);
			invokeAll(leftTask, rightTask);
		}
	}

	@Before(Tx.class)
	private void sendProcess(int start2, int end2, String[] memberIds2, RisebdCouponRule couponRule2) {
		List<String> waitSendMemberIds = new ArrayList<String>();
		if (waitSendMemberIds.size() == 0) {
			logger.info("需要发送的会员数量为0.");
			return;
		}
		//当优惠券数量不为空，且 总数量=已领取的数量，无需再次发送
		if (couponRule2.getCouponNum() != 0 && couponRule2.getCouponNum() == couponRule2.getReceiveNum()) {
			logger.info("此优惠券规则已被领取完couponNum={},receiveNum = {}", couponRule2.getCouponNum(),
					couponRule2.getReceiveNum());
			return;
		}
		// 得到所有可用的此规则下的优惠券集合No
		for (int i = start2; i <= end2; i++) {
			String memberId = memberIds2[i];
			waitSendMemberIds.add(memberId);
			// 得到
			String openid = CacheService.getOpenidByMemberId(memberId);
			String templateId = "";
			String topColor = "";
			String jumpUrl = "";
			DataItem dataItem = new DataItem();
			CompleteService.sendTemplate(openid, templateId, topColor, jumpUrl, dataItem);

		}

		// 取出可以发送的优惠券,可设置的优惠券
		List<String> usableCouponNos = CacheService.getCouponNoRuleUsable(couponRule2.getId(), couponRule2.getStatus(),
				couponRule2.getCouponNum(), waitSendMemberIds.size() - 1);
		logger.info("本地待发送的会员waitSendMemberId={},取出发送的usableCouponNos={}", JsonKit.toJson(waitSendMemberIds),
				JsonKit.toJson(usableCouponNos));
		// 开始发送
		// 设置会员优惠券表
		int[] batchSaveMemberSize = RisebdCouponMember.me.batchSave(waitSendMemberIds, usableCouponNos,
				couponRule2.getCouponNum(), couponRule2.getCouponNo(), couponRule2.getTitle(),
				couponRule2.getConponForm(), couponRule2.getCouponAmount(), couponRule2.getId(), couponRule2.getType(),
				couponRule2.getLimitAmount(), 1, couponRule2.getCouponStartTime(), couponRule2.getCouponEndTime());
		logger.info("批量加入会员优惠券表batchSaveMemberSize={}", batchSaveMemberSize);
		//设置优惠券表的状态
		if (0 != couponRule2.getCouponNum()) {//当设置非无限大时才会更新
			RisebdCoupon.me.batchUpdate(usableCouponNos, waitSendMemberIds, couponRule2.getId(), couponRule2.getType());
		}
		//本次发送的人数
		int recycleSize = 0;
		if (usableCouponNos.size() < waitSendMemberIds.size() && couponRule2.getCouponNum() != 0) {//当领取人数大于可以领取的优惠券并且，优惠券总数大于0时，领取数量为可领取的优惠券
			recycleSize = usableCouponNos.size();
		} else {//否则则为会员人数
			recycleSize = waitSendMemberIds.size();
		}
		//设置已被领取的优惠券
		RisebdCouponRule.me.updateReceiveNum(couponRule2.getId(), recycleSize);
		//删除可以发送的优惠券
		long remCouponSize = CacheService.removeCouponNoRuleUsable(couponRule2.getId(), couponRule2.getStatus(),
				usableCouponNos);
		logger.info("删除规则下已领取的优惠券remCouponSize={}", remCouponSize);
	}

}
